package com.tanxiuxin.YiWaiMai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanxiuxin.YiWaiMai.common.Result;
import com.tanxiuxin.YiWaiMai.dto.DishDto;
import com.tanxiuxin.YiWaiMai.pojo.Category;
import com.tanxiuxin.YiWaiMai.pojo.Dish;
import com.tanxiuxin.YiWaiMai.pojo.DishFlavor;
import com.tanxiuxin.YiWaiMai.pojo.SetmealDish;
import com.tanxiuxin.YiWaiMai.service.CateGoryService;
import com.tanxiuxin.YiWaiMai.service.DishFlavorService;
import com.tanxiuxin.YiWaiMai.service.DishService;
import com.tanxiuxin.YiWaiMai.service.SetmealDishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *  菜品管理
 */

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CateGoryService cateGoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     *      新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto){
        dishService.saveAndFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryName() + "_1";
        redisTemplate.delete(key);
        return Result.success("新增菜品成功");
    }


    /**
     *      菜品分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page , int pageSize , String name) {
        // 构造分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        // 构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(!StringUtils.isEmpty(name), Dish::getName, name);
        // 添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 执行查询
        dishService.page(pageInfo, queryWrapper);
        // 对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage , "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item)-> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item , dishDto);
            Long categoryId = item.getCategoryId(); // 分类的 id
            Category category = cateGoryService.getById(categoryId);// 根据 id 查分类对象
            if (category.getName() != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        // 执行查询
        dishService.page(pageInfo, queryWrapper);
        return Result.success(dishDtoPage);
    }

    /**
     *       根据 id 来查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable("id") Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     *      修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(dishDto);

        // 清理所有菜品数据
        // Set keys = redisTemplate.keys("dish_*");
        // redisTemplate.delete(keys);

        // 清理某个分类下的菜品缓存
        String key = "dish_" + dishDto.getCategoryName() + "_1";
        redisTemplate.delete(key);

        return Result.success("新增菜品成功");
    }

    /**
     *     根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public Result<List<Dish>> list(Dish dish){
//        // 构造查询条件
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId() != null , Dish::getCategoryId , dish.getCategoryId());
//        // 添加条件，查询状态为：1 （起售状态）的菜品
//        queryWrapper.eq(Dish::getStatus , 1);
//        // 添加排序条件
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        List<Dish> list = dishService.list(queryWrapper);
//
//        return Result.success(list);
//    }

    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList = null;

        // 动态构造 key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        // 先从redis 中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null) {
            // 如果存在，直接返回
            return Result.success(dishDtoList);
        }

        // 如果不存在，查询数据库，并将查询到的菜品数据缓存到 redis
        // 构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null , Dish::getCategoryId , dish.getCategoryId());
        // 添加条件，查询状态为：1 （起售状态）的菜品
        queryWrapper.eq(Dish::getStatus , 1);
        // 添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item , dishDto);
            Long categoryId = item.getCategoryId();
            Category category = cateGoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            Long dishId = item.getId(); // 当前菜品的 id

            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId , dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key , dishDtoList , 60 , TimeUnit.SECONDS);
        return Result.success(dishDtoList);
    }

    /**
     *    单个删除和批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(Long... ids){
        Result<String> message = dishService.removeAndFlavor(ids);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getCategoryId , ids);
        List<Dish> list = dishService.list(queryWrapper);
        String key = null;
        for (Dish dish : list) {
            Category category = cateGoryService.getById(dish);
            String categoryName = category.getName();
            key = "dish_" + categoryName + "_1";
            if (redisTemplate.opsForValue().get(key) == null){
                redisTemplate.opsForValue().set(key , 555 , 60 , TimeUnit.MINUTES);
            }else {
                redisTemplate.delete(key);
            }
        }
        return message;
    }

    /**
     *    起售和停售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> stop( @PathVariable("status")Integer status , Long... ids){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId , ids);
        List<Dish> dishList = dishService.list(queryWrapper);
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getDishId , ids);
        List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);
        if (list.size() == 0){
            for (Dish dish : dishList) {
                dish.setStatus(status);
                dishService.updateById(dish);
                Long categoryId = dish.getCategoryId();
                Category category = cateGoryService.getById(categoryId);
                String key = "dish_" + category.getName() + "_1";
                if (redisTemplate.opsForValue().get(key) != null) {
                    redisTemplate.delete(key);
                }
            }
            return Result.success("停售成功");
        }
        return Result.error("套餐中正在出售，无法停售");
    }


}
